<?php

/**
 * @name SysconfigController
 * @desc 控制器
 */
class SysconfigController extends AdminCommonController
{
    /**
     * 默认动作
     */
    public function indexAction()
    {
        echo "Hello sysconfig";
        return false;
    }

    //配置列表
    public function configAction(){

        $params = $this->jsonData();

        $row = $params['pageSize'] ?? 100;
        $page = $params['page'] ?? 1;

        $sysConfigModel = SysConfigModel::getSingleton();
        $list = $sysConfigModel->db
            ->where(['is_show'=> 1])
            ->order('id desc')
            ->limit(($page - 1) * $row, $row)
            ->select();
        $total = $sysConfigModel->db
            ->where([])
            ->count();

        foreach($list as &$val){
        }

        $data = [
            'list' => $list,
            'total' => intval($total),
            'current'   => intval($page),
            'pageSize'  => intval($row),
            'page'  => intval($page)
        ];

        $this->ajaxReturn(0, '', $data);
    }


    //修改普通配置
    public function editAction(){
        $params = $this->jsonData();

        if(!$params || empty($params) || !isset($params['id'])){
            $this->ajaxReturn(400, '修改失败');
        }

        $index = $params['index'];
        //每日交易时间格式判断
        if(in_array($index, ['trade_time_s', 'trade_time_e']) && !preg_match('/^[0-9]{2}:[0-9]{2}$/', (string) $params['value'])){
            $this->ajaxReturn(400, '时间格式不正确，正确格式如：16:15');
        }

        $sysConfigModel = SysConfigModel::getSingleton();
        $res = $sysConfigModel->update(['id'=> $params['id']],
            ['value'=> $params['value'], 'description'=> $params['description'], 'update_time'=> time()]
        );
        if(!$res){
            $this->ajaxReturn(400, '修改失败');
        }

        $this->ajaxReturn(0, '修改成功');
    }

    //修改算力配置
    public function editautoAction(){
        $params = $this->jsonData();

        if(!$params || empty($params) || !isset($params['index']) || !isset($params['data'])){
            $this->ajaxReturn(400, '修改失败,请刷新页面重试');
        }

        $index = $params['index'];
        $data = [];
        foreach($params['data'] as $val){
            $data[$val['index']] = $val['value'];
        }
        $data = json_encode($data);

        $sysConfigModel = SysConfigModel::getSingleton();
        $res = $sysConfigModel->update(['index'=> $index],
            ['value'=> $data, 'update_time'=> time()]
        );

        if(!$res){
            $this->ajaxReturn(400, '修改失败');
        }
        $this->ajaxReturn(0, '修改成功');
    }
}
